﻿using System;
using Dimebrain.TweetSharp.Core.Extensions;
using Newtonsoft.Json;

namespace Dimebrain.TweetSharp.Model.Twitter.Converters
{
    /// <summary>
    /// This converter exists to convert geo-spatial coordinates.
    /// </summary>
    public class TwitterGeoLocationConverter : TwitterConverterBase
    {
        private const string _geoTemplate =
            "\"geo\":{{\"type\":\"Point\",\"coordinates\":[{0}, {1}]}}";

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (!(value is GeoLocation))
            {
                return;
            }

            var location = (GeoLocation) value;
            var json = _geoTemplate.FormatWith(location.Latitude,location.Longitude);
            writer.WriteValue(json);
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            if(reader.Value == null || reader.Value.ToString().IsNullOrBlank())
            {
                return null;
            }

            // 37.78029, -122.39697
            var coordinates = reader.Value.ToString().Replace(",", "")
                .Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);

            if(coordinates.Length != 2)
            {
                return null;
            }

            var latitude = Convert.ToDouble(coordinates[0]);
            var longitude = Convert.ToDouble(coordinates[1]);

            return new GeoLocation(latitude, longitude);
        }

        public override bool CanConvert(Type objectType)
        {
            var t = (IsNullableType(objectType))
                        ? Nullable.GetUnderlyingType(objectType)
                        : objectType;

            return typeof(GeoLocation).IsAssignableFrom(t);
        }
    }
}